<template>
	<view class="content">
		<view>一寸照片</view>
    <view class="bgred">
      <view @click="downloadimg">下载</view>
      <canvas canvas-id="copyCanvas" class="copyCanvas" style="position:absolute;top:-8999px;left:-8999px;"></canvas>
      <view id="copy-canvas" class="my_canvas" >
        <image data-type="image" :data-url="imgUrl"  class="showImg my_draw_canvas"  :src="imgUrl"></image>
      </view>
      <view class="showImg2">
        <canvas style="width:100%;height:100%" canvas-id="myCanvas"></canvas>
      </view>
      <view @click="pictureClick" class="btn">上传头像</view>
    </view>
	</view>
</template>

<script>
  let sysInfo = uni.getSystemInfoSync();
	let SCREEN_WIDTH = sysInfo.screenWidth;
	let SCREEN_HEIGHT = sysInfo.windowHeight + 40;
  import {getAccessToken, getbodyhead, getanalysis} from '../../util/api.js'
  import base64src from './base64src.js'
  import {savePoster} from './saveImg.js'
  // https://blog.csdn.net/qq_35443423/article/details/122198209
  // https://blog.csdn.net/weixin_36236774/article/details/114049344
  // https://github.com/shutterstock/changeDPI
  // https://github.com/davidchambers/Base64.js
  // https://blog.csdn.net/qq_20567691/article/details/100044142
  let IMG_RATIO
  let ratio = 295/413
	export default {
		data() {
			return {
				imgUrl: '',
        imageW : 295,
        imageH : 413
			}
		},
		onLoad() {

		},
		methods: {
      pictureClick () {
        const _this = this;
        let typelist = ['album']
        uni.chooseImage({
            count: 1,
            // sizeType: ['original', 'compressed'],
            sourceType: typelist, //这要注意，camera掉拍照，album是打开手机相册
            // crop: {
            //   width: 320,
            //   height: 320
            // },
            success: (res)=> {
                console.log(res);
                _this.toBase64(res.tempFilePaths[0])
                // let formData = new FormData();
                // let imgObj = res.tempFiles[0]
                // formData.append('file', imgObj);
                wx.uploadFile({
                  url: 'http://192.168.22.94:8083/txy/zjz/generate',
                  filePath: res.tempFilePaths[0],//获取的图片临时路径
                  name: 'file',//图片标识,后台可用标识获取该图片,也可以用下标获取
                  success(res) {
                    console.log(JSON.parse(res.data));
                    },
                    fail(res){
                      console.log(res);
                    }
                });
                // getanalysis(param).then(res => {
                //   console.log(res)
                // })
                // _this.previewImg(res.tempFilePaths[0])
                // let url = 'data:image/jpeg;base64,'+wx.getFileSystemManager().readFileSync(res.tempFilePaths[0], "base64");
                // let url = res.tempFilePaths[0];
                
                // _this.headUrl = url
                // _this.imgUrl = res.tempFilePaths[0];
                // let imgUrl = res.tempFilePaths[0];
                // _this.previewImg(imgUrl)
            }
        });
      },
      toBase64(file) {
        let _this = this
        uni.getFileSystemManager().readFile({
            filePath: file, //选择图片返回的相对路径
            encoding: 'base64', //编码格式
            success: res => {
                // 成功的回调
                // 'data:image/jpeg;base64,'
                
                let base64 = res.data;
                _this.buildImg(base64)
            }
        });
      },
      buildImg(imgstr) {
        uni.showLoading({
          title: "图片加载中...",
        });
        let _this = this;
        let param = {
          image: imgstr,
        }
        
        getAccessToken({
          grant_type: 'client_credentials',
          client_id: '8rXGybqwf34AvX9OmwUhITeI',
          client_secret: 'A7W7W0biuHKD2oh9wavUPxVyTZUoVU9b'
        }).then(res=> {
          console.log(res)
          let data = res.data;
          let param = {
            access_token: data.access_token,
            image: imgstr,
          }
          Promise.all([getanalysis(param),getbodyhead(param)]).then(([headPos,bodyImg]) => {
            let widthInfo = headPos.data.person_info[0]
            let location = _this.imgwidthsum(widthInfo)
            // let foreground = decodeURIComponent(bodyImg.data.foreground)
            let foreground = bodyImg.data.foreground
            _this.previewImg('data:image/png;base64,' + foreground, location)
            uni.hideLoading();
          })
        })
      },
      imgwidthsum(data) {
        let location = data.location;
        let body_parts = data.body_parts
        return {
          top_head: body_parts.top_head, 
          left_shoulder: body_parts.left_shoulder,
          right_shoulder: body_parts.right_shoulder
        }
        console.log(location, body_parts.top_head, body_parts.left_shoulder, body_parts.right_shoulder)
      },
      downloadimg() {
        savePoster(this.imgUrl)
      },
      previewImg(imageSrc, location) {
        // this.imgUrl = imageSrc;
        let _this = this
        base64src(imageSrc).then(filePath => {

          uni.getImageInfo({
            src: filePath,
            success: function success(res) {
              console.log(2)
              
              let imgH = res.height;
              let imgW = res.width;
              /* 图片的宽高比  */
              IMG_RATIO = imgW / imgH;
              // let IMG_RATIO = imgW / imgH;
              let IMG_REAL_W,IMG_REAL_H
              // if (IMG_RATIO < 1 && (SCREEN_HEIGHT - 120) * IMG_RATIO < SCREEN_WIDTH - 10) {
              //   IMG_REAL_W = (SCREEN_HEIGHT - 120) * IMG_RATIO;
              //   IMG_REAL_H = SCREEN_HEIGHT - 120;
              // } else {
              //   IMG_REAL_W = SCREEN_WIDTH - 10;
              //   IMG_REAL_H = IMG_REAL_W / IMG_RATIO;
              // }
              
              IMG_REAL_H = 413
              IMG_REAL_W = IMG_REAL_H*IMG_RATIO
              let canH = imgW * IMG_REAL_H / IMG_REAL_W
              const ctx = uni.createCanvasContext("myCanvas", _this);
              _this.imageW = IMG_REAL_W
              _this.imageH = IMG_REAL_H
              console.log(canH,'0000')
              ctx.setFillStyle('red')
              ctx.fillRect(0,0,IMG_REAL_W,IMG_REAL_H)
              ctx.drawImage(imageSrc, 0, 0, IMG_REAL_W, IMG_REAL_H);
              ctx.draw(true,(ret)=>{						 
                uni.showToast({
                  icon:'success',
                  mask:true,
                  title: '绘制完成',
                });
                console.log(location)
                // let x = location.right_shoulder.x //203
                // let y = location.top_head.y // 386
                // let x1 = location.left_shoulder.x //888
                let x = location.right_shoulder.x //203
                let y = location.top_head.y-250 // 386
                let x1 = location.left_shoulder.x //888
                // 获取画布要裁剪的位置和宽度   均为百分比 * 画布中图片的宽度    保证了在微信小程序中裁剪的图片模糊  位置不对的问题 canvasT = (_this.cutT / _this.cropperH) * (_this.imageH / pixelRatio)
              var canvasW = ((x1 - x) / imgW) * IMG_REAL_W;
              // var canvasH = ((y1 - y) / imgH) * IMG_REAL_H;
              var canvasH = canvasW/ratio // canvasW * 413 / 295
              var canvasL = (x / imgW) * IMG_REAL_W;
              var canvasT = (y / imgH) * IMG_REAL_H;
              console.log(canvasL, canvasT, canvasW, canvasH)
                uni.canvasToTempFilePath({ // 保存canvas为图片
                  x: canvasL,
                  y: canvasT,
                  width: canvasW, //canvasH,
                  height: canvasH, //canvasH,
                  destWidth: 295,
                  destHeight: 413,
                  // x: canvasL,
                  // y: canvasT,
                  // width: canvasH, //canvasH,
                  // height: canvasH, //canvasH,
                  // destWidth: 295,
                  // destHeight: 413,
                  canvasId: 'myCanvas',
                  quality: 1,
                  complete: function(res) {
                    // 在H5平台下，tempFilePath 为 base64, // 图片提示跨域 H5保存base64失败，APP端正常输出临时路径
                    console.log(res.tempFilePath)		
                    _this.imgUrl = res.tempFilePath
                    
                  } ,
                })
              });
            }
          })
        })
        

      }
		}
	}
</script>

<style>
@import './index.css';
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
</style>
